<?php

namespace app\queue\redis\vipOrder;

use app\services\RequestService;
use plugin\admin\app\model\RechargeLog;
use plugin\admin\app\model\VipOrder as VipOrderModel;
use plugin\admin\app\model\YbUser;
use support\Log;
use Webman\RedisQueue\Consumer;

class VipOrder implements Consumer
{
    // 要消费的队列名
    public $queue = 'vip-order-reward';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        $customer_id = YbUser::getCustomerId($data['customer_number'],$data['appid']);
        $order = VipOrderModel::where('id',$data['order_id'])->first();

        if (empty($order) || $order->is_reward== 1){
            return;
        }
        if (!empty($customer_id)){
            $balance = RequestService::updateBalance($data['appid'],$customer_id,$data['price'],$data['reward_create_time']);
            if (!empty($balance['status']) && $balance['status'] =='success') {
                VipOrderModel::where('id',$data['order_id'])->update(['is_reward'=>1,'reward_create_time'=>$data['reward_create_time']]);
                RechargeLog::create([
                    'appid' =>$data['appid'],
                    'customer_id' => $customer_id,
                    'price' => $data['price'],
                    'vip_order_id' => $data['order_id'],
                ]);
            }else{
                Log::error('会员升级奖励发放失败：' . json_encode($balance, JSON_UNESCAPED_UNICODE));
            }
        }
    }


    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {

    }
}